package com.finance.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gyw on 2017/4/26.
 */
public class BeanToMapUtils {
    protected static final Logger logger = LoggerFactory.getLogger(BeanToMapUtils.class);

    /**
     * getFileds获取所有public 属性<br/>
     * getDeclaredFields 获取所有声明的属性<br/>
     * @param bean
     * @return 将某个类及其继承属性全部添加到Map中
     */
    public static Map<String,Object> beanToMap(Object bean){
        Map<String,Object> result = new HashMap<String,Object>();
        if(bean == null){
            return result;
        }

        Field[] fields = bean.getClass().getDeclaredFields();
        if(fields == null || fields.length == 0){
            return result;
        }

        for(Field field:fields){
            //重置属性可见(而且一般属性都是私有的)，否则操作无效
            boolean accessible = field.isAccessible();
            if(!accessible){
                field.setAccessible(true);
            }

            //获取属性名称及值存入Map
            String key = field.getName();
            try {
                result.put(key, field.get(bean));
            } catch (IllegalArgumentException e) {
                logger.error(e.getMessage(),e);
            } catch (IllegalAccessException e) {
                logger.error(e.getMessage(),e);
            }

            //还原属性标识
            field.setAccessible(accessible);
        }
        return result;
    }
}
